import request from '@/utils/request'

// 提交记录接口返回类型
export interface SubmissionResult {
  id: number
  status: number
  status_display: string
  status_class: string
  problem_title: string
  language_display: string
  time_display: string
  memory_display: string
  submit_time: string
  code: string
  compile_output: string | null
  test_cases_passed: number
  total_test_cases: number
  username: string
  nick_name: string
}

// API 响应类型
export interface ApiResponse<T> {
  code: number
  msg: string
  data: T
  count?: number
}

// 查询参数类型
export interface SubmissionListParams {
  problem?: number
  page: number
  page_size: number
}

const codeApi = {
  // 提交代码
  submitCode(data: { problem: number; language: number; code: string }): Promise<ApiResponse<SubmissionResult>> {
    return request.post<ApiResponse<SubmissionResult>>('/submission/submit/', data)
  },

  // 获取提交记录列表
  async getSubmissionList(params: SubmissionListParams): Promise<ApiResponse<SubmissionResult[]>> {
    const response = await request.get<any>('/submission/', { params })
    console.log('API Response:', response)
    
    // 确保返回的数据符合预期格式
    if (response && response.code === 200) {
      return {
        code: response.code,
        msg: response.msg,
        data: Array.isArray(response.data) ? response.data : [],
        count: response.count || 0
      }
    }
    
    // 如果响应格式不正确，返回空数据
    return {
      code: response.code || 500,
      msg: response.msg || '获取数据失败',
      data: [],
      count: 0
    }
  },

  // 获取提交记录详情
  getSubmission(id: number): Promise<ApiResponse<SubmissionResult>> {
    return request.get<ApiResponse<SubmissionResult>>(`/submission/${id}/`)
  }
}

export default codeApi
